import { MODEL_JWT_KEY, companyId } from './constants';

let app = null;

export function request(url, req = {}, method = 'POST', needCache = false) {
    return new Promise(function (resolve, reject, complete) {
        let header = {};
        let jwt = getFromModel(MODEL_JWT_KEY);
        if (jwt) {
            header.Authorization = jwt;
        }
        header.companyId = companyId;
        wx.request({
            url: "http://doctorsop.niuduo.com/recipecloud/mobileEmployee/selectDocterMessage/",
            data: req,
            method: method,
            header,
            success: (res) => {
                // console.log(res);
                res.data = [{
                    patientAppid: 1,
                    docterId: 2,
                    newMsgCount: 10,
                    msgType: 0,
                    chatContent: "但是分别是大部分比赛的发放开始",
                    lastUpdateAt: new Date()
                }]
                resolve(res)
                // console.log('on data res = ', res);
                if (res.statusCode !== 200) {
                    wx.showToast({
                        title: '后台错误: ' + res.statusCode,
                    });
                    reject && reject(url);
                    return;
                }

                if (res.data) {
                    if (res.data.errorMsg) {
                        //wx.hideToast();
                        wx.showToast({
                            image: '../../images/delete.png',
                            title: res.data.errorMsg,
                        });
                        reject && reject(url);
                    } else {
                        if (needCache) {
                            // console.log("save response to cache:", res.data);
                            wx.setStorage({
                                key: toKey(url, req),
                                data: res.data
                            })
                        }
                        //wx.hideToast();
                        resolve(res.data)
                    }
                } else {
                    //wx.hideToast();
                    // wx.showToast({
                    //   title: '后台错误',
                    // });   
                    res.data = [{
                        patientAppid: 1,
                        docterId: 2,
                        newMsgCount: 10,
                        msgType: 0,
                        chatContent: "但是分别是大部分比赛的发放开始",
                        lastUpdateAt: new Date()
                    }]
                    // reject && reject(url)
                }

            },
            fail: (res) => {
                //wx.hideToast();
                // wx.showToast({
                //   title: '后台错误',
                // });
                // console.log('request fail', url, res);
                reject && reject(res)
            },
            complete: (res) => {
                //console.log('request complete',url, res);
            }

        })
    })
}

export function cacheRequest(url, req = {}, method = 'POST') {
    var value = wx.getStorageSync(toKey(url, req));
    if (value) {
        return new Promise((resolve, reject) => {
            return resolve(value);
        });
    }
    else {
        return request(url, req, method, true);
    }
}

export function getFromModel(key) {
    if (!app) {
        app = getApp();
    }
    if (app && app.model[key]) {
        return app.model[key];
    }

    let data = wx.getStorageSync(key);
    if (data && app) {
        app.model[key] = data;
    }
    return data;
}

export function saveToModel(key, data, onSucess = () => { }, onFail = () => { }) {
    if (!app) {
        app = getApp();
    }
    if (app) app.model[key] = data;
    setTimeout(() => {
        wx.setStorage({
            key: key,
            data: data,
            success: onSucess,
            fail: onFail
        })
    }, 0);

}

function toKey(url, req) {
    let key = url;
    if (req) {
        key = key + JSON.stringify(req)
    }
    return key;
}

/**
 * 节流函数
 * 
 */
export function throttle(func, wait) {

    var context, args, timeout, result, previous, later;
    previous = 0;

    later = function () {
        previous = new Date();
        timeout = null;
        result = func.apply(context, args);
    };

    return function () {
        var now = new Date(),
            remaining = wait - (now - previous);

        context = this;
        args = arguments;

        if (remaining <= 0) {
            clearTimeout(timeout);
            timeout = null;
            previous = now;
            result = func.apply(context, args);
        } else if (!timeout) {
            timeout = setTimeout(later, remaining);
        }

        return result;
    };
}

// 时间戳转换
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

export function shiftHttp(http) {

    return http.replace(/^http/, 'https')
}

export function getCurrentDateTime( currDate ) {
    const date = currDate ? new Date(currDate) : new Date();
    const month = date.getMonth()+ 1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const time = `${date.getFullYear()}-${month>9 ? '' : '0'}${month}-${day>9 ? '' : '0'}${day} ${hours>9 ? '' : '0'}${hours}:${minutes>9 ? '' : '0'}${minutes}:${seconds>9 ? '' : '0'}${seconds}`
    return time
  }
